package com.example.caoh.service.impl.sys;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.caoh.entity.SysResources;
import com.example.caoh.entity.SysUser;
import com.example.caoh.mapper.SysResourcesMapper;
import com.example.caoh.service.impl.BaseService;
import com.example.caoh.service.sys.SysResourcesService;
import com.example.caoh.service.sys.SysUserService;

@Service("resourcesService")
public class SysResourcesServiceImpl extends BaseService<SysResources> implements SysResourcesService {

	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysResourcesMapper sysResourcesMapper;
	
	
	@Override
	public List<SysResources> loadUserResources(Integer userId) {
		SysUser user = sysUserService.getOneById(userId);
		List<SysResources> list = findResourcesByRoleId(user.getRoleId());
		return list;
	}

	public List<SysResources> findResourcesByRoleId(String roleId) {
		List<String> resourceIds = sysResourcesMapper.findResIdByRoleId(roleId);
		List<SysResources> list = new ArrayList<>();
		for(String resourceId:resourceIds) {
			SysResources o = sysResourcesMapper.selectByPrimaryKey(resourceId);
			list.add(o);
		}
		return list;
	}

	@Override
	public List<Map<String, Object>> getMenuList(String roleId, boolean needChecked) {
		try {
			List<Map<String, Object>> roleMenu = sysResourcesMapper.listRoleMenu(roleId);
			List<Map<String, Object>> resultMenu = menuTreeData();
			checkMenu(resultMenu, roleMenu, needChecked);
			// 去掉没被选中的
			deleteUncheckMenu(resultMenu, needChecked);
			return resultMenu;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 查找菜单tree data数据
	* @Title: menuTreeData 
	* @Description: TODO(这里用一句话描述这个方法的作用) 
	* @return List<Map<String,Object>>
	 */
	public List<Map<String,Object>> menuTreeData(){
	    List<Map<String,Object>> resultList=new ArrayList<Map<String,Object>>();
	    try {
	        SysResources queryEntity=new SysResources();
	        queryEntity.setParentId("0");
	        
	        List<SysResources> list=sysResourcesMapper.select(queryEntity);
	        for(SysResources cycleEntity:list){
	            Map<String,Object> item=new HashMap<String, Object>();
	            item.put("name", cycleEntity.getResourceName());
	            item.put("open", false);
	            item.put("linkurl", cycleEntity.getResourceUrl());
	            item.put("id", cycleEntity.getId());
	            item.put("parentId", cycleEntity.getParentId());
	            item.put("sort", cycleEntity.getSort());
	            item.put("clazz", cycleEntity.getClazz());
	            item.put("menuLevel", cycleEntity.getMenuLevel());
	            
	            //查找子节点
	            SysResources queryItem=new SysResources();
	            queryItem.setParentId(cycleEntity.getId());
	            resultList.add(item);
	            findLeaf(item,queryItem);
	            
	            
	        }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
	    return resultList;
	}
	
	public void  findLeaf(Map<String,Object> map,SysResources entity){
	    List<SysResources> list=sysResourcesMapper.select(entity);
	    List<Map<String,Object>> resultList=new ArrayList<Map<String,Object>>();
	    if(list.size()>0){
	        for(SysResources cycleEntity:list){
	            Map<String,Object> item=new HashMap<String, Object>();
	            item.put("name", cycleEntity.getResourceName());
	            item.put("open", false);
	            item.put("linkurl", cycleEntity.getResourceUrl());
	            item.put("id", cycleEntity.getId());
	            item.put("parentId", cycleEntity.getParentId());
                item.put("sort", cycleEntity.getSort());
                //查找子节点
                SysResources queryItem=new SysResources();
                queryItem.setParentId(cycleEntity.getId());
                findLeaf(item,queryItem);
                resultList.add(item);
            }
	        map.put("children", resultList);
	    }
	    
	}
	
	@SuppressWarnings("unchecked")
	public void checkMenu(List<Map<String, Object>> menuTotal, List<Map<String, Object>> roleMenu,
			boolean needChecked) {
		try {
			for (Map<String, Object> map : menuTotal) {
				for (Map<String, Object> rolemap : roleMenu) {
					if (needChecked) {
						if (map.get("id").toString().equals(rolemap.get("menuId").toString())) {
							map.put("checked", true);
						}
					} else {
						if (map.get("id").toString().equals(rolemap.get("menuId").toString())) {
							map.put("needChecked", true);
						}
					}

				}
				if (map.containsKey("children")) {
					checkMenu((List<Map<String, Object>>) map.get("children"), roleMenu, needChecked);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 去除没被选中的菜单
	 * 
	 * @Title: deleteUncheckMenu
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param menuTotal
	 *            void
	 */
	@SuppressWarnings("unchecked")
	public void deleteUncheckMenu(List<Map<String, Object>> menuTotal, boolean needChecked) {
		try {
			for (int i = 0; i < menuTotal.size(); i++) {
				if (needChecked) {
					if (menuTotal.get(i).containsKey("checked")) {
						if (menuTotal.get(i).containsKey("children")) {
							deleteUncheckMenu((List<Map<String, Object>>) menuTotal.get(i).get("children"),
									needChecked);
						}

					} else {
						menuTotal.remove(menuTotal.get(i));
						i--;
					}
				} else {
					if (menuTotal.get(i).containsKey("needChecked")) {
						if (menuTotal.get(i).containsKey("children")) {
							deleteUncheckMenu((List<Map<String, Object>>) menuTotal.get(i).get("children"),
									needChecked);
						}

					} else {
						menuTotal.remove(menuTotal.get(i));
						i--;
					}
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
}
